import store from 'store/index'
import CryptoJS from 'crypto-js';
const BaseUrl = process.env.VUE_APP_BASE_URL;
const env = process.env.ENV_TYPE

// 封装请求接口函数
// 只有请求结果返回 200 的时候，才会resolve，否则reject
const request = (url, method = "POST", data = {}) => {
	uni.onNetworkStatusChange(function(res) {
		if (!res.isConnected) {
			uni.showToast({
				title: '网络连接不可用！',
				icon: 'none'
			});
		}
		return false
	});
	uni.showLoading({
		title: '加载中...',
		mask: true
	});
	let header = data.header || {}
	let token = encodeURIComponent((uni.getStorageSync('token') || ''))
	if (data.token) {
		token = encodeURIComponent(data.token)
	}
	header['Authorization'] = 'Bearer ' + token
	header['Form-Token'] = encrypt(new Date().getTime() + '#' + url)
	let pages = getCurrentPages();  // 获取加载的页面
	let currentPage = pages[pages.length-1];  // 获取当前页面的对象
	data.current_page = currentPage.route;  // 当前页面url
	return new Promise((resolve, reject) => {
		if (url.substr(0, 4) != 'http') {
			let suffix = '/'
			if (url.substr(0, 1) == '/') {
				suffix = ''
			}
			url = BaseUrl + suffix + url
		}
		uni.request({
			url: url,
			method,
			data,
			header: header,
			success: function(res) {
				uni.hideLoading();
				if (res.statusCode == 200) {
					if (res.data.code == -1) {
						uni.showToast({
							title: res.data.message,
							duration: 3000,
							icon: 'none'
						});
						reject(res.data);
					} else {
						resolve(res.data);
					}
				} else if (res.statusCode == 401) {
					let msg = '错误信息'
					if (res.data) {
						msg = res.data.message
					}
					uni.removeStorageSync('userinfo')
					uni.removeStorageSync('token')
					uni.navigateTo({
						url: '/pages/login/login'
					})
				} else {
					let msg = '错误信息'
					if (res.data) {
						msg = res.data.message
					}
					uni.showToast({
						title: msg,
						duration: 3000,
						icon: 'none'
					});
					reject(res.data);

				}
			},
			fail: function(err) {
				uni.hideLoading();
				reject(err)
			}
		})
	});
}

const wxcloud = (url, method = "POST", data = {}) => {
	let header = data.header || {}
	let token = encodeURIComponent((uni.getStorageSync('token') || ''))
	if (data.token) {
		token = encodeURIComponent(data.token)
	}
	header['Authorization'] = 'Bearer ' + token
	header['Form-Token'] = encrypt(new Date().getTime() + '#' + url)
	header['X-WX-SERVICE'] = "jsswbak"
	let pages = getCurrentPages();  // 获取加载的页面
	let currentPage = pages[pages.length-1];  // 获取当前页面的对象
	data.current_page = currentPage.route;  // 当前页面url
	uni.onNetworkStatusChange(function(res) {
		if (!res.isConnected) {
			uni.showToast({
				title: '网络连接不可用！',
				icon: 'none'
			});
		}
		return false
	});
	uni.showLoading({
		title: '加载中...',
		mask: true
	});
	return new Promise((resolve, reject) => {
		const option = {
			config: {
				env: "prod-xxxxxx"
			},
			path: url.substring(0, 1) == '/' ? url : '/' + url,
			header: header,
			method: method,
			data: data,
			success: (res) => {
				uni.hideLoading();
				if (res.statusCode === 200) {
					if (res.data.code == -1) {
						uni.showToast({
							title: res.data.message,
							duration: 3000,
							icon: 'none'
						});
						reject(res.data);
					} else {
						resolve(res.data);
					}
				} else if (res.statusCode === 401) {
					let msg = '错误信息'
					if (res.data) {
						msg = res.data.message
					}
					uni.removeStorageSync('userinfo')
					uni.removeStorageSync('token')
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}
			},
			fail: (err) => {
				uni.hideLoading();
				reject(err)
			}
		}
		wx.cloud.callContainer(option)
	});
}

/**
 * 加密方法
 * @param word
 * @returns {string}
 */
//设置秘钥和秘钥偏移量
const encrypt = (word) => {
	let srcs = CryptoJS.enc.Utf8.parse(word);
	let encrypted = CryptoJS.AES.encrypt(srcs, CryptoJS.enc.Utf8.parse("9EB34E79B03D7B79"), {
		iv: CryptoJS.enc.Utf8.parse("2a5effe115ec5aca"),
		mode: CryptoJS.mode.CBC
	})
	return encrypted.toString();
}

const getrefreshToken = () => {
	return new Promise((resolve, reject) => {
		const refreshToken = uni.getStorageSync('refreshToken')

		// 使用 expiredToken 请求新的 token
		uni.request({
			url: BaseUrl + '/api/GetRefreshToken',
			method: 'POST',
			header: {
				'Authorization': `Bearer ${refreshToken}`
			},
			data: {
				refreshToken: refreshToken
			},
			success: function(res) {
				if (res.statusCode == 200) {
					uni.setStorageSync('token', res.data.data.accessToken);
					resolve(res.data.accessToken);
				} else {
					reject(res);
				}
			},
			fail: function(err) {
				reject(err);
			}
		});
	});
}

// 上传图片
const uploadFile = async (file, option) => {
	let header = option.header || {}
	let token = encodeURIComponent((uni.getStorageSync('token') || ''))
	if (option.token) {
		token = encodeURIComponent(option.token)
	}
	let url = option.url ? option.url : BaseUrl + "/api/oss";
	header['Authorization'] = 'Bearer ' + token
	header['Form-Token'] = encrypt(new Date().getTime() + '#' + url)
	header['X-WX-SERVICE'] = "jsswbak"
	const formData = {
		start: 0,
		size: file.size,
		name: file.name ? file.name : '',
		type: file.type ? file.type : 'image'
	};
	uni.compressImage({
		src: file.path,
		compressedWidth: 300,
		success(res) {
			file.path = res.tempFilePath
			uni.getFileSystemManager().readFile({
				filePath: file.path,
				encoding: 'base64',
				position: 0,
				success(res) {
					formData.chunk = res.data
					if (env == 'wxcloud') {
						wx.cloud.callContainer({
							config: {
								env: "prod-8g0vp102fb01b958"
							},
							path: url.replace(BaseUrl, ''),
							header: header,
							method: "POST",
							data: formData,
							success: (res) => {
								console.log(res.data)
								//option.success(res.data, 0);
							},
							fail: (err) => {
								console.log(err)
								if(err){
									option.fail('上传失败');
								}
								
							},
							complete: (res) => {
								
								const json = res.data
								if (json.code == 1) {
									option.complete(json, 0);
								} else {
									option.fail(json.message);
								}
							}
						})
					} else {
						uni.request({
							url: url,
							header: header,
							data: formData,
							method: 'POST',
							success: (res) => {
								option.success(res.data, 0);
							},
							fail: (err) => {
								console.log(err)
								if(err){
									option.fail('上传失败');
								}
							},
							complete: (res) => {
								const json = res.data
								if (json.code == 1) {
									option.complete(json, 0);
								} else {
									option.fail(json.message);
								}
							}
						})
					}
				}
			});
		},
		fail(err) {
			console.log(err)
		}
	})


	/*
	uni.uploadFile({
		url: url,
		filePath: file.path,
		name: 'chunk',
		header: header,
		formData: formData, // 可以在这里添加额外的表单数据
	});
	*/
};

module.exports = {
	request: env == 'wxcloud' ? wxcloud : request,
	uploadFile
};